<?php
/**
 * 果林
 *
 * Created	: 2010-10-22
 * Modified : 2010-10-22
 * @author  : 陈立强
 */
class FruitForest {

	public static $info=null;
	public static $proficiencyType = 2;
	public static $cfg = null;
	public static $cfgName = 'build/fruit_forest';

	/**
	 * 初始化玩家的果林信息
	 * @param int $uid
	 */
	public static function init ($uid)
	{
		global $DB, $L;
		if (!$uid) {
			return false;
		}

		$data = array();
		$lvl  = self::getLvl($uid);

		$fruitForestCfg = self::$cfg;
		$holeNum        = $fruitForestCfg[$lvl]['hole_num'];

		$DB->beginTransaction();
		for ($pos=1; $pos<=$holeNum; $pos++) {
			// 更新数据
			$data = array(
				'uid'		=> $uid,
				'pos'		=> $pos,
				'status'	=> 0,
				'now_fruit'	=> 0,
				'end_growup_time' => 0,
				'harvest_time' => 0,
				'num'		=> '',
				'vigorous'	=> 0,
			);
			$ret = $DB->insert('fruit_forest', $data);
			if (!$ret) {
				$DB->rollBack();
				break;
			}
		}

		if ($ret) {
			$DB->commit();
		}
		return $ret;
	}

	/**
	 * 获取一块树坑的信息
	 * @param int $uid 用户ID
	 * @param int $pos 树坑的位置
	 * @param int $updateRipeInfo 是否同时更新已成熟的果树信息
	 */
	public static function getHoleInfo($uid, $pos, $updateRipeInfo=1)
	{
		global $DB, $L;
		$sql    = 'SELECT * FROM fruit_forest WHERE uid=:uid and pos=:pos';
		$params = array('pos'=>(int)$pos, 'uid'=>(int)$uid);
		$info   = self::$info = $DB->getValue($sql, $params);
		if (false === $info) {
			return array(
				'val' => false,
				'msg' => $L['Failure']
			);
		}
		$now = time();
		if ($updateRipeInfo
				&& $info['end_growup_time']>0 && $info['end_growup_time']<=$now
		) {
			$ret = self::endGrowUp($uid, $pos);
			if ($ret['val']) {
				$info['num'] = $ret['data']['num'];
			}
		} elseif ($updateRipeInfo && empty($info['num'])
				&& $info['harvest_time']>0 && $info['harvest_time']<=$now
		) {
			$ret = self::mature($uid, $pos);
			if ($ret['val']) {
				$info['num'] = $ret['data']['num'];
			} else {
				
			}
		}
		if (is_string($info['num'])) {
			$info['num'] = json_decode($info['num'], true) ;
		}
		if ($info['now_fruit'] > 0) {
			$fruitList = C('item/fruit');
			$cfg = $fruitList[$info['now_fruit']];
			$info['title'] = $cfg['title'];
			$info['seed_id'] = $cfg['seed_id'];
		} else {
			$info['title'] = '';
		}
		if ($info['now_fruit'] > 0) {
			$info['grow_need_time'] = $cfg['grow_need_time'];
			$info['ripe_need_time'] = $cfg['ripe_need_time'];
		}
		return $info;
	}

	/**
	 * 获取果林等级
	 * @param int $uid 用户ID
	 */
	public static function getLvl($uid)
	{
		global $DB;
		$sql = 'SELECT fruit_forest_lvl FROM user WHERE uid='.(int)$uid;
		return (int)$DB->getValue($sql);
	}

	/**
	 * 获取果林信息
	 * @param int $uid
	 */
	public static function getInfo($uid)
	{
		global $DB, $L;
		$fruitForestLvl = self::getLvl($uid);
		$fruitForest    = self::$cfg;

		$result['val'] = $fruitForestLvl!==false ? true : false;
		if ($fruitForestLvl !== false) {
			$result['data'] = $fruitForest[$fruitForestLvl];
			$result['data']['lvl'] = $fruitForestLvl;
			$result['data']['fruit_max_vogorous'] = $G['fruit_max_vogorous'];
		} else {
			$result['msg'] = $L['Failure'];
			$data = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('fruit_forest_get_info', $data);
		}
		return $result;
	}

	/**
	 * 获取所有树坑信息
	 * @param int $uid
	 * @param int $to_uid 获取他人的列表
	 */
	public static function getList($uid, $to_uid=null)
	{
		global $DB, $L, $max_plowland_num;

		$to_uid = (int)$to_uid;
		if ($to_uid) {
			$uid = $to_uid;
		}

		$sql   = 'SELECT * FROM fruit_forest WHERE uid='.(int)$uid;
		$tmpList = $DB->getList($sql);

		$list = array();
		$now  = time();

		$refreshTime = $now + 86400;
		$cfgList = C('item/fruit');
		foreach($tmpList as $record) {
			if (empty($record['num']) && $record['end_growup_time'] > 0
						&& $record['end_growup_time']<=$now) {
				$ret = self::endGrowUp($uid, $record['pos']);
				if ($ret['val']) {
					$record['status'] = $ret['data']['status'];
					$record['end_growup_time'] = $ret['data']['end_growup_time'];
					$record['harvest_time'] = $ret['data']['harvest_time'];
				}
			} elseif (empty($record['num']) && $record['harvest_time'] > 0
						&& $record['harvest_time']<=$now) {
				$ret = self::mature($uid, $record['pos']);
				if ($ret['val']) {
					$record['num'] = $ret['data']['num'];
					$record['status'] = $ret['data']['status'];
				}
			} elseif ('' != $record['num']) {
				$record['num'] = json_decode($record['num'], true) ;
			}
			if ($record['now_fruit']) {
				$cfg = $cfgList[$record['now_fruit']];
				$record['title'] = $cfg['title'];
				$record['seed_id'] = $cfg['seed_id'];
			}
			$list[$record['pos']] = $record;
			if ($record['end_growup_time'] > 0) {
				$refreshTime = min($refreshTime, $record['end_growup_time']);
			}
			if ($record['harvest_time'] > 0) {
				$refreshTime = min($refreshTime, $record['harvest_time']);
			}
		}
		return array(
			'val'  => true,
			'data' => $list
//			'data' => array(
//				'list' => $list,
//				'refresh_time' => $refresh_time
//			)
		);
	}

	/**
	 * 果林扩建
	 * @param int $uid
	 */
	public static function extend($uid)
	{
		global $DB, $L;

		$sql = 'SELECT ticket,fruit_forest_extend_times FROM user WHERE uid='.$uid;
		$user = $DB->getValue($sql);

		$cfg = C('common/need_ticket');
		if ($user['fruit_forest_extend_times'] >= $cfg['fruit_forest_max_extend']) {
			return array(
				'val' => false,
				'msg' => $L['fruit_forest_extend_time_is_max']
			);
		}

		$needTicket = $cfg['fruit_forest_extend_need'][$user['fruit_forest_extend_times']+1];
		// 点券不足
		if ($needTicket > $user['ticket']) {
			return array(
				'val' => false,
				'msg' => $L['ticket_not_enough']
			);
		}

		$DB->beginTransaction();
		// 将扩建次数加1,且扣除对应的点券
		$sql = 'UPDATE user SET ticket=ticket-'.$needTicket.',fruit_forest_extend_times=fruit_forest_extend_times+1 WHERE uid='.$uid;
		$ret = $DB->exeSql($sql);
		if ($ret !== false) {
			$ret = true;
		}

		// 增加一块树坑
		if ($ret) {
			$sql = 'SELECT MAX(pos) FROM fruit_forest WHERE uid='.$uid;
			$pos = $DB->getValue($sql);
			$data = array(
				'uid'       => $uid,
				'pos'       => $pos + 1,
				'status'	=> 0,
				'now_fruit' => 0,
				'end_growup_time' => 0,
				'harvest_time' => 0,
				'num'       => '',
				'vigorous'  => 0,
			);
			$ret = $DB->insert('fruit_forest', $data);
		}

		$result['val'] = (bool)$ret;
		if ($ret) {
			// 处理成功,提交事务
			$DB->commit();
			$ret = self::getList($uid);
			$result['data'] = $ret['data'];
		} else {
			// 出错,回滚数据操作
			$DB->rollBack();
			$result['msg'] = $L['Failure_Update'];
			$data = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('fruit_forest_extend', $data);
		}

		return $result;
	}

	/**
	 * 升级(增筑果林)
	 * @param int $uid
	 * @return boolean
	 */
	public static function lvlUp($uid)
	{
		global $DB, $L;
		$lvl = self::getLvl($uid);
		$nextLvl = $lvl+1;

		$fruitForestCfg = self::$cfg;

		// 是否已升级至满级
		end($fruitForestCfg);
		$maxLvl = key($fruitForestCfg);
		if ($nextLvl>$maxLvl) {
			return array(
				'val' => false,
				'msg' => $L['fruit_forest_is_max_lvl']
			);
		}

		$user = User::read($uid);
		// 需要金钱不足
		if ($user['coin'] < $fruitForestCfg[$lvl]['need_coin']) {
			return array(
				'val' => false,
				'msg' => $L['coin_not_enough']
			);
		}
		// 角色等级是否满足
		if ($user['lvl'] < $fruitForestCfg[$lvl]['need_mc_lvl']) {
			return array(
				'val' => false,
				'msg' => $L['mc_lvl_is_not_enough']
			);
		}

		$DB->beginTransaction();

		$data = array(
			'fruit_forest_lvl' => $nextLvl
		);
		$ret = $DB->update('user', $data, 'uid='.$uid);

		// 扣除金钱
		if ($ret) {
			$sql = 'UPDATE user SET coin=coin-'.$fruitForestCfg[$lvl]['need_coin'].' WHERE uid='.$uid;
			$ret = $DB->exeSql($sql);
		}

		$result['val'] = $ret;
		if ($ret) {
			// 增加新树坑
			$data = array();

			$holeNum     = $fruitForestCfg[$lvl]['hole_num'];
			$nextHoleNum = $fruitForestCfg[$nextLvl]['hole_num'];

			// 添加上级之后pos到达下一次最大的数量的耕地
			$posList = array();
			$insert  = 1;
			$sql = 'SELECT MAX(pos) FROM fruit_forest WHERE uid='.$uid;
			$pos = $DB->getValue($sql);
			$addPos = $nextHoleNum - $holeNum;
			for ($i=1; $i<=$addPos; $i++) {
				$pos += $i;
				// 更新数据
				$data = array(
					'uid'       => $uid,
					'pos'       => $pos,
					'status'	=> 0,
					'now_fruit' => 0,
					'end_growup_time' => 0,
					'harvest_time' => 0,
					'num'       => '',
					'vigorous'  => 0,
				);
				$ret = $DB->insert('fruit_forest', $data);
				if (!$ret) {
					$insert = 0;
					$result['val'] = $ret;
					$DB->rollBack();
					$result['msg'] = $L['Failure_Insert'];
					$data = var_export($DB->errors, true);
					// 记录错误日志
					Log::save('fruit_forest_lvl_up', $data);
					break;
				}
				$posList[] = $pos;
			}
			if ($insert) {
				$DB->commit();
				$result['data'] = array(
					'lvl' => $nextLvl,
					'pos' => $posList
				);
			}
		} else {
			$DB->rollBack();
			$result['msg'] = $L['Failure'];
			$data = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('fruit_forest_lvl_up', $data);
		}
		return $result;
	}

	/**
	 * 种植果树苗
	 * @param int $uid
	 * @param int $seedId 果实ID
	 * @param int $pos
	 */
	public static function plant($uid, $seedId, $pos)
	{
		global $DB, $L;
		$info = self::getHoleInfo($uid, $pos, 0);
		if (isset($info['val']) && false === $info['val']) {
			return array(
				'val' => false,
				'msg' => $L['fruit_forest_isnot_assarted']
			);
		}

		//-- 对应位置的树坑是否有作物
		if ($info['now_fruit']) {
			return array(
				'val' => false,
				'msg' => $L['fruit_forest_is_planted']
			);
		}

		//-- 果树苗不存在
		$cfgList = C('item/seed_list');
		if (!isset($cfgList[$seedId])) {
			return array(
				'val' => false,
				'msg' => $L['no_such_fruit_seed']
			);
		}
		$fruitId = $cfgList[$seedId];
		$cfgList = C('item/fruit');
		$cfgInfo = $cfgList[$fruitId];

		// 水果信息
		if (is_null($cfgInfo)) {
			return array(
				'val' => false,
				'msg' => $L['no_such_fruit_seed']
			);
		}

		//-- 前置作物熟练度等级是否达到要求
		if ($cfgInfo['pre_product']) {
			$sql = 'SELECT lvl FROM user_proficiency WHERE uid='.$uid.' AND item_id='.$cfgInfo['pre_product'];
			$lvl = $DB->getValue($sql);
			if (!$lvl || $lvl < $G['pre_proficiency_lvl']) {
				return array(
					'val' => false,
					'msg' => $L['pre_product_lvl_not_enough']
				);
			}
		}

		//-- 牧场等级是否达到要求
		$sql = 'SELECT lvl,coin FROM user WHERE uid='.$uid;
		$user = $DB->getValue($sql);
//		if ($user['lvl'] < $cfgInfo['need_mc_lvl']) {
//			return array(
//				'val' => false,
//				'msg' => $L['mc_lvl_is_not_enough']
//			);
//		}

		//-- 是否有足够的金钱
		if ($user['coin'] < $cfgInfo['seed_price']) {
			return array(
				'val' => false,
				'msg' => $L['coin_not_enough']
			);
		}

		//-- 季节是否满足树苗的种植要求
		$plant_season = $cfgInfo['plant_season'];
		if (false === strpos($plant_season, (string)Game::$data['season'])) {
			return array(
				'val' => false,
				'msg' => $L['fruit_cannot_plant_now_season']
			);
		}

		//-- 是否有足够的树苗
//		$sql = 'SELECT depot_id,num FROM depot WHERE uid=:uid and item_id=:item_id';
//		$param = array(
//			'uid' => $uid,
//			'item_id' => $seedId,
//		);
//		$itemInfo = $DB->getValue($sql, $param);
//		$num      = $itemInfo['num'];
//		if ($num <= 0) {
//			return array(
//				'val' => false,
//				'msg' => $L['seed_isnot_enough']
//			);
//		}

		$DB->beginTransaction();

		// 种植该作物成熟需要时间
		$needTime = $cfgInfo['grow_need_time'];
		// 作物结束成长的时间点
		$endGrowupTime = time() + $needTime;

		// 更新树坑信息
		$data = array(
			'status'	=> 1,
			'now_fruit' => $fruitId,
			'end_growup_time' => $endGrowupTime,
			'harvest_time' => 0,
			'harvest_times' => $cfgInfo['harvest_times'],
			'num'    => '',
		);
		$where = 'ffid='.$info['ffid'];
		$ret   = $DB->update('fruit_forest', $data, $where);

		//-- 扣除金钱
		if ($ret) {
			$sql = 'UPDATE user SET coin=coin-'.$cfgInfo['seed_price'].' WHERE uid='.$uid;
			$ret = $DB->exeSql($sql);
		}

		$result['val'] = $ret;
		if ($ret) {
			// 处理成功,提交事务
			$DB->commit();
			$data['end_growup_time'] = $needTime;
			$result['data'] = $data + $info;
		} else {
			// 出错,回滚数据操作
			$DB->rollBack();
			$result['msg'] = $L['Failure_Update'];
			$data = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('fruit_forest_plant', $data);
		}

		return $result;
	}

	/**
	 * 结束成长期,进入成熟期
	 * @param int $uid 用户ID
	 * @param int $pos 树坑的位置
	 */
	public static function endGrowUp($uid, $pos)
	{
		global $DB, $L, $G;

		if (self::$info) {
			$info = self::$info;
		}

		if (!self::$info || self::$info['pos'] != $pos) {
			$info = self::getHoleInfo($uid, $pos, 0);
		}

		// 当前树坑是空闲状态
		if (empty($info['now_fruit'])) {
			return array(
				'val' => false,
				'msg' => $L['fruit_forest_hole_is_idle']
			);
		}

		// 作物不在成长期
		if ($info['end_growup_time'] == 0) {
			return array(
				'val' => false,
				'msg' => $L['fruit_hasnot_in_glowup']
			);
		}

		// 未到成熟期时间
		if ($info['end_growup_time'] > time()) {
			return array(
				'val' => false,
				'msg' => $L['fruit_hasnot_end_glowup']
			);
		}

		$DB->beginTransaction();

		// 作物信息
		$fruitList    = C('item/fruit');
		$harvest_time = $fruitList[$info['now_fruit']]['ripe_need_time'];
		$harvest_time = $harvest_time + $info['end_growup_time'];

		// 如果生成的成熟时间也是在过去时,则使果树成熟,生成果实
		if ($harvest_time <= time()) {
			self::$info['harvest_time'] = $harvest_time;
			$ret = self::mature($uid, $pos);
			if ($ret['val']) {
				$DB->commit();
				return $ret;
			} elseif ($ret['msg'] == $L['Failure_Update']) {
				$DB->rollBack();
			}
		}

		$data = array(
			'status'	=> 2,
			'end_growup_time' => 0,
			'harvest_time' => $harvest_time,
			'vigorous' => $G['fruit_tree_initial_vigorous'],
		);
		$where = 'ffid='.(int)$info['ffid'];
		$ret   = $DB->update('fruit_forest', $data, $where);
		$result['val'] = $ret;
		if ($ret) {
			$DB->commit();
			$result['data'] = array(
				'end_growup_time' => 0,
				'harvest_time'	=> $harvest_time,
				'vigorous'		=> $G['fruit_tree_initial_vigorous'],
				'status'		=> 2,
			);
		} else {
			$DB->rollBack();
			$result['msg'] = $L['Failure_Update'];
			$data = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('fruit_forest_end_growup', $data);
		}

		return $result;

	}

	/**
	 * 结束成熟期,使果实结果
	 * @param int $uid 用户ID
	 * @param int $pos 树坑的位置
	 */
	public static function mature($uid, $pos)
	{
		global $DB, $L, $G;

		$now = time();

		if (self::$info) {
			$info = self::$info;
		}

		if (!self::$info || self::$info['pos'] != $pos) {
			$info = self::getHoleInfo($uid, $pos, 0);
		}


		// 位置是空的，没有种植果树
		if ($info['now_fruit'] == 0) {
			return array(
				'val' => false,
				'msg' => $L['fruit_forest_hole_is_idle']
			);
		}

		// 已经生成成熟的数据
		if ($info['num'] != '') {
			return array(
				'val' => true,
				'msg' => $L['Success'],
				'data' => array(
					'num' => $info['num']
				)
			);
		}

		// 还未进入成熟期
		if ($info['harvest_time'] == 0) {
			return array(
				'val' => false,
				'msg' => $L['fruit_hasnot_in_ripetime']
			);
		}

		// 未到成熟时间
		if ($info['harvest_time'] > $now) {
			return array(
				'val' => false,
				'msg' => $L['fruit_hasnot_ripe']
			);
		}


		//-- 生成成熟的作物及数量
		$cfgList   = C('item/fruit');
		$cfgInfo = $cfgList[$info['now_fruit']];
		$baseOutput = $cfgInfo['base_output'];
		$rnd = round(rand (60, 100)/100, 2);
		$vigAddition = $info['vigorous'] * $G['fruit_vogorous_param'];
		$output     = $baseOutput * $rnd + $vigAddition;
		// 根据最终产量数量取配置结果
		$outputCfg = C('output/fruit_output');
		$num = getRangeKeyValue($output, $outputCfg);
		$numStr = json_encode($num);

		$data = array(
			'end_growup_time'	=> 0,
			'num'				=> $numStr,
			'status'			=> 2,
		);
		$where = 'ffid='.(int)$info['ffid'];
		$ret   = $DB->update('fruit_forest', $data, $where);
		$result['val'] = $ret;
		if ($ret) {
			$result['data'] = array(
				'num' => $num,
				'status' => 2,
			);
		} else {
			$result['msg'] = $L['Failure_Update'];
			$data = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('fruit_forest_mature', $data);
		}

		return $result;

	}

	/**
	 * 收获指定果树的果实
	 * @param int $uid 用户ID
	 * @param int $pos 树坑的位置
	 */
	public static function harvest($uid, $pos)
	{
		global $DB, $L, $G;

		$now = time();

		$info = self::getHoleInfo($uid, $pos, 1);
		if (isset($info['val']) && false === $info['val']) {
			return array(
				'val' => false,
				'msg' => $L['fruit_forest_isnot_assarted']
			);
		}

		// 位置是空的，没有种植果树
		if ($info['now_fruit'] == 0) {
			return array(
				'val' => false,
				'msg' => $L['fruit_forest_hole_is_idle']
			);
		}

		// 未到成熟时间
		if (!$info['num']) {
			return array(
				'val' => false,
				'msg' => $L['fruit_hasnot_ripe']
			);
		}

		if (!$info['num']) {
			$ret = self::mature($uid, $pos);
			if ($ret['val']) {
				$info['num'] = $ret['data']['num'];
			}
		}
		
		$freeCapacity = Depot::getFreeCapacity($uid);
		// 仓库容量不足
		if ($freeCapacity == 0) {
			return array(
				'val' => false,
				'msg' => $L['not_enough_grid_in_depot']
			);
		}
		// 产品是否全部收获
		$allHarvest = ($freeCapacity >= array_sum($info['num']));

		//-- 收获增加活力值
		if ($allHarvest) {
			$cfg = self::$cfg;
			$lvl = self::getLvl($uid);
			$vigorous = $info['vigorous'] + rand($G['harvest_add_vogorous'][0], $G['harvest_add_vogorous'][1]);
			if ($vigorous > $G['fruit_max_vogorous']) {
				$vigorous = $G['fruit_max_vogorous'];
			}
		}


		$DB->beginTransaction();

		$ret = false;


		$fruitList = C('item/fruit');
		$fruitInfo = $fruitList[$info['now_fruit']];
		$fruitName = $fruitInfo['title'];
		//-- 收获物品进入仓库
		$qualityCfg = $G['quality_id'];
		$harvest = array();
		// 产品从小到大进行收获
		ksort($info['num']);
		foreach ($info['num'] as $quality => $num) {
			if ($num == 0) {
				unset($info['num'][$quality]);
				continue;
			}
			if ($freeCapacity == 0) {
				break;
			}
			if ($freeCapacity < $num) {
				$num = $freeCapacity;
				$info['num'][$quality] -= $num;
			} else {
				unset($info['num'][$quality]);
			};
			$data = array(
				'title'		=> $info['title'],
				'item_id'	=> $info['now_fruit'],
				'item_type'	=> $fruitInfo['item_type'],
				'num'		=> $num,
				'quality'	=> $quality,
				'lvl'		=> $fruitInfo['lvl']
			);
			$ret = Depot::in($uid, $data);
			if (!$ret['val']) {
				$DB->rollBack();
				return $ret;
			}
			$harvest[$quality] = $num;
			
			// 当前收获后已经没有容量 了
			$freeCapacity -= $num;
			if ($freeCapacity == 0) {
				break;
			}
		}

		$DB->setTransactionState(false);
		//-- 收获获得种植熟练度
		if ($ret && $allHarvest) {
			$proExp = $fruitInfo['add_proficiency'];// 获取的熟练度值
			$ret = User::addProficiency($uid, $proExp, $info['now_fruit'], 2);
			if (!$ret['val']) {
				$DB->rollBack();
				return $ret;
			} else {
				$ret = true;
			}
		}
		//-- 收获获得经验
		if ($ret && $allHarvest) {
			$exp = $fruitInfo['add_exp'];
			$ret = User::addExp($uid, $exp);
			if (!$ret['val']) {
				$DB->rollBack();
				return $ret;
			} else {
				$ret = true;
			}
		}

		// 是否可以获取惊喜宝箱
		if ($ret && $allHarvest && getRandResult($G['harvest_get_box_rate'])) {
			$item_id = 11006;
			$lvl = 0;
			$mailContent = sprintf($L['harvest_get_box'], $info['title']);
			$return = TreasureBox::get($uid, $item_id, $lvl, null, $mailContent);
			$ret = $return['val'];
			$inMail = $return['data']['in_mail'];
			$getTreasureBox = true;
		} else {
			$inMail = false;
			$getTreasureBox = false;
		}
		$DB->setTransactionState(true);


		// 收获次数
		$harvest_times = $info['harvest_times'] - 1;
		if ($harvest_times <= 0) {
			$harvest_time = 0;
			$harvest_times = 0;
		} else {
			// 下次收获时间点
			$harvest_time  = $now + $fruitInfo['ripe_need_time'];
		}

		//-- 修改果树信息
		if ($ret) {
			// 全部收获清空林地信息
			if ($allHarvest) {
				$data = array(
					'end_growup_time' => 0,
					'num'			=> '',
					'harvest_time'	=> $harvest_time,// 下一次收获的时间
					'harvest_times'	=> $harvest_times,// 已收获次数
					'vigorous'		=> $vigorous
				);
			} else {
				$data = array(
					'num'	=> json_encode($info['num']),
				);
			}
			$where = 'ffid='.(int)$info['ffid'];
			$ret   = $DB->update('fruit_forest', $data, $where);
			if ($ret !== false) {
				$ret = true;
			}
		}
		$result['val'] = (boolean)$ret;
		if ($ret) {
			$DB->commit();
			$info['title'] = $fruitName;
			$result['data'] = $data + $info;
			$result['data']['get_treasure_box'] = $getTreasureBox;
			$result['data']['in_mail'] = $inMail;
			$result['data']['all_harvest'] = $allHarvest;
			if (!$allHarvest) {
				$result['data']['harvest'] = $harvest;
			}
		} else {
			$DB->rollBack();
			$result['msg'] = $L['Failure'];
			$data = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('fruit_forest_harvest', $data);
		}

		return $result;
	}

	/**
	 * 使用营养剂
	 * @param int $uid 用户ID
	 * @param int $pos 果树的位置
	 * @param int $box_id 营养剂的道具箱ID
	 */
	public static function useNutrient($uid, $pos, $box_id)
	{
		global $DB, $L, $G;

		$box_id = (int)$box_id;
		$sql = 'SELECT uid,item_id,item_type,num FROM props_box WHERE box_id='.$box_id;
		$boxInfo = $DB->getValue($sql);
		//-- 是否有足够的化肥;
		if (!$boxInfo) {
			return array(
				'val' => false,
				'msg' => $L['item_not_enough']
			);
		}
		// 不是营养剂
		if ($boxInfo['item_type']!=32 || $boxInfo['uid']!=$uid) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}

		$info = self::getHoleInfo($uid, $pos);
		if (isset($info['val']) && false === $info['val']) {
			return array(
				'val' => false,
				'msg' => $L['fruit_forest_isnot_assarted']
			);
		}
		// 是否有作物
		if ($info['now_fruit'] == 0) {
			return array(
				'val' => false,
				'msg' => $L['fruit_forest_hole_is_idle']
			);
		}

		$DB->beginTransaction();

		// 扣除一个化肥
		if ($boxInfo['num'] > 1) {
			$sql = 'UPDATE props_box SET num=num-1 WHERE box_id='.$box_id;
		} else {
			$sql = 'DELETE FROM props_box WHERE box_id='.$box_id;
		}
		$ret = $DB->exeSql($sql);
		if ($ret !== false) {
			$ret = true;
		}

		if ($ret) {
			$cfg = C('item/nutrient');
			$addVigorous = $cfg[$nutrient_id]['add_vigorous'];
			$return = self::addVigorous($uid, $pos, $addVigorous);
			$ret = $return['val'];
			$msg = $return['msg'];
		}

		$result['val'] = (bool)$ret;
		if ($ret) {
			$DB->commit();
			$result['data'] = self::getHoleInfo($uid, $pos);
		} else {
			$DB->rollBack();
			$result['msg'] = isset($msg) ? $msg : $L['Failure_Update'];
			$data = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('fruit_forest_harvest', $data);
		}
		return $result;
	}

	/**
	 * 给一个果树添加活力值
	 * @param int $uid 用户ID
	 * @param int $pos 位置
	 * @param int $value 添加的活力值
	 */
	public static function addVigorous($uid, $pos, $value=0)
	{
		global $DB, $L;

		$maxVigorous = 100;// 活力值上限

		$where = 'uid=:uid and pos=:pos';
		$sql   = 'SELECT vigorous FROM fruit_forest WHERE '.$where;
		$params = array(
			'uid' => (int)$uid,
			'pos' => (int)$pos,
		);
		$vigorous = $DB->getValue($sql, $params);
		$vigorous += $value;
		if ($vigorous>$maxVigorous) {
			return array(
				'val' => false,
				'msg' => $L['vigorous_is_max']
			);
		}
		$sql = 'UPDATE fruit_forest SET vigorous=:vigorous'
			  .' where '.$where;
		$params = array(
			'uid' => (int)$uid,
			'pos' => (int)$pos,
			'vigorous' => (int)$vigorous,
		);
		$ret = $DB->exeSql($sql, $params);

		$result['val'] = (boolean)$ret;
		if ($ret) {
			$result['msg'] = $L['Success'];
		} else {
			$result['msg'] = $L['Failure'];
			$data = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('fruit_forest_add_vigorous', $data);
		}

		return $result;
	}
	
	/**
	 * 增加收获次数
	 * @param $uid
	 * @param $pos
	 */
	public static function addHarvestTimes($uid, $pos) 
	{
		global $DB, $L, $G;
		
		$pos = (int)$pos;
		
		$sql = 'SELECT ffid,add_harvest_times FROM fruit_forest WHERE uid='.$uid.' AND pos='.$pos;
		$posInfo = $DB->getValue($sql);
		
		$needCoin = $G['add_harvest_times_param1'] + ($posInfo['add_harvest_times'] * $G['add_harvest_times_param2']);
		$userInfo = User::read($uid);
		// 金钱不足
		if ($userInfo['coin'] < $needCoin) {
			return array(
				'val' => false,
				'msg' => sprintf($L['need_ticket_not_enough'], $needCoin)
			);
		}
		
		$DB->beginTransaction();
		
		// 增加收获次数
		$sql = 'UPDATE fruit_forest SET harvest_times=harvest_times+1 WHERE ffid='.$posInfo['ffid'];
		$ret = $DB->exeSql($sql);
		// 扣除金钱
		if ($ret) {
			$sql = 'UPDATE user SET coin=coin-'.$needCoin.' WHERE uid='.$uid;
			$ret = $DB->exeSql($sql);
		}
		
		$result['val'] = (bool)$ret;
		if ($ret) {
			$DB->commit();
			$result['data'] = self::getHoleInfo($uid, $pos);
		} else {
			$DB->rollBack();
			$result['msg'] = $L['Failure_Update'];
			$data = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('fruit_forest_harvest', $data);
		}
		return $result;
	}

	/**
	 * 获取树苗列表
	 * @param $uid
	 */
	public static function getSeedList($uid)
	{
		return Town::getFruitSeedList($uid);
	}

	/**
	 * 获取营养剂列表
	 * @param $uid
	 */
	public static function getNutrientList($uid)
	{
		global $DB, $L;

		$sql = 'SELECT item_id,title,num FROM depot WHERE uid='.$uid.' AND item_type=32';
		$list = $DB->getList($sql);

		if (!$list) $list = array();

		$data = array();
		foreach ($list as $k=>$item) {
			$data[] = $item;
		}

		return array(
			'val' => true,
			'data' => $data,
		);
	}

	/**
	 * 清理
	 * @param int $uid 用户ID
	 * @param int $pos 位置
	 */
	public static function eradicate($uid, $pos)
	{
		global $DB, $L, $G;

		$DB->beginTransaction();

		$data = array(
			'status'			=> 0,
			'now_fruit'			=> 0,
			'end_growup_time'	=> 0,
			'harvest_time'		=> 0,
			'harvest_times'		=> 0,
			'num'				=> '',
			'vigorous'			=> 0,
		);
		$pos = (int)$pos;
		$ret = $DB->update('fruit_forest', $data, 'uid='.$uid.' and pos='.$pos);
		$ret!==false && $ret = true;

		$result['val'] = (bool)$ret;
		if ($ret) {
			$DB->commit();
			$result['data'] = self::getHoleInfo($uid, $pos);
		} else {
			$DB->rollBack();
			$result['msg'] = $L['Failure_Update'];
			$data = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('fruit_forest_harvest', $data);
		}
		return $result;
	}
	
	/********************************************
	 * 互动部分
	 ********************************************/
	
	/**
	 * 偷窃
	 * @param int $uid
	 * @param int $to_uid
	 * @param int $pos
	 */
	public static function steal($uid, $to_uid, $pos) 
	{
		global $DB, $L, $G;
		
		if ($uid == $to_uid) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}
		
		
		$posInfo = self::getHoleInfo($to_uid, $pos);
		// 还未成熟,不能偷窃
		if ($posInfo['status'] != 2) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}
		// 已经被偷过了
		if ($posInfo['is_stolen']) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}
		
		$now = time();
		
		$userInfo = User::read($uid, 'lvl,seriate_steal_times,last_steal_time,energy_point,in_prison');
		if ($userInfo['in_prison']) {
			$sql = 'SELECT * FROM prison WHERE uid='.$uid;
			$prisonInfo = $DB->getValue($sql);
			if (!$prisonInfo['can_interactive']) {
				return array(
					'val' => false,
					'msg' => $L['cannot_steal_in_prison']
				);
			}
		}
		
		// 能量点不够
		if (!$userInfo['energy_point']) {
			return array(
				'val' => false,
				'msg' => $L['energy_point_not_enough']
			);
		}
		
		// 判断是否好友
		if (!Friend::isFriend($uid, $to_uid)) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}
		
		$toUserInfo = User::read($uid, 'lvl,seriate_steal_times');
		
		// 载入互动操作配置
		C('common/interactive');
		
		// 上次偷窃时间到现在超过24小时,连续偷窃次数清零
		if ($userInfo['last_steal_time'] < ($now-86400)) {
			$stealTimes = 0;
			$seriateStealParam = $G['seriate_steal_param'][0];
		} else {
			$stealTimes = $userInfo['seriate_steal_times'] + 1;
			if (isset($G['seriate_steal_param'][$userInfo['seriate_steal_times']])) {
				$seriateStealParam = $G['seriate_steal_param'][$userInfo['seriate_steal_times']];
			} else {
				$seriateStealParam = 0;
			}
		}
		
		if ($seriateStealParam) {
			$differenceLvl = abs($userInfo['lvl'] - $toUserInfo['lvl']);
			$cfgList = C('item/fruit');
			$cfg = $cfgList[$posInfo['now_fruit']];
			$successRate = $G['base_steal_success_rate'][$cfg['lvl']]
							* $G['difference_lvl_steal_param'][$differenceLvl]
							* $G['seriate_steal_param'][$stealTimes];
			$success = getRandResult($successRate);
		} else {// 参数为0,肯定失败
			$success = false;
		}
		
		$DB->beginTransaction();
		$DB->setTransactionState(false);
		
		$result['data'] = array(
			'success' => $success
		);
		
		if ($success) {
			$addition = 0;
			foreach ($posInfo['num'] as $quality=>$num) {
				$addition += ($num * $G['steal_coin_prize_param'][$quality]);
			}
			// 获得金钱奖励
			$getCoin = $G['steal_coin_prize_base_value'] + $addition;
			$sql = 'UPDATE user SET coin=coin+'.$getCoin.',energy_point=energy_point-1,
					seriate_steal_times='.$stealTimes.',last_steal_time='.$now.' WHERE uid='.$uid;
			$ret = $DB->exeSql($sql);
			if ($ret) {
				$result['data']['get_coin'] = $getCoin;
			}
			
			if ($ret) {
				$sql = 'UPDATE farm SET is_stolen=1 WHERE fid='.$posInfo['fid'];
				$ret = $DB->exeSql($sql);
			}
		} else {
			// 关进监狱
			$ret = Prison::detain($uid);
			
			// 扣除能量点
			if ($ret) {
				$sql = 'UPDATE user SET energy_point=energy_point-1,seriate_steal_times=0 WHERE uid='.$uid;
				$ret = $DB->exeSql($sql);
			}
		}
		
		$DB->setTransactionState(true);

		$result['val'] = (bool)$ret;
		if ($ret) {
			$DB->commit();
		} else {
			$DB->rollBack();
			$result['msg'] = $L['Failure_Update'];
			$data = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('fruit_forest_steal', $data);
		}
		return $result;
	}
	
	/**
	 * 除虫
	 * @param $uid
	 * @param $to_uid 被除虫的果园主人用户ID
	 * @param $pos 果园位置
	 */
	public static function worm($uid, $to_uid, $pos) 
	{
		global $DB, $L, $G;
		
		$posInfo = self::getHoleInfo($to_uid, $pos);
		// 只在成熟期才能除虫 
		if ($posInfo['status'] != 2) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}
		// 已经除过虫了
		if ($posInfo['is_wormed']) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}
		$userInfo = User::read($uid, 'lvl,seriate_steal_times,last_steal_time,energy_point');
		// 能量点不够
		if (!$userInfo['energy_point']) {
			return array(
				'val' => false,
				'msg' => $L['energy_point_not_enough']
			);
		}
		
		// 判断是否好友
		if (!Friend::isFriend($uid, $to_uid)) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}
		
		$now = time();
		
		$DB->beginTransaction();
		$DB->setTransactionState(false);
		
		// 载入互动操作配置
		C('common/interactive');
		
		$cropList = C('item/fruit');
		$cfg = $cropList[$posInfo['now_fruit']];
		// 减少时间
		$reduceTime = round($cfg['ripe_need_time'] * $G['worm_reduce_time']);
		$sql = 'UPDATE fruit_forest SET is_wormed=1,harvest_time=harvest_time-'.$reduceTime.' WHERE fid='.$posInfo['ffid'];
		$ret = $DB->exeSql($sql);
		
		// 扣除能量点
		if ($ret) {
			$sql = 'UPDATE user SET energy_point=energy_point-1 WHERE uid='.$uid;
			$ret = $DB->exeSql($sql);
		}
		
		// 增加经验
		if ($ret) {
			$ret = User::addExp($uid, $G['worm_get_exp']);
		}
		
		$DB->setTransactionState(true);

		$result['val'] = (bool)$ret;
		if ($ret) {
			$DB->commit();
			$result['data'] = array(
				'info'		=> self::getHoleInfo($to_uid, $pos),
				'get_exp'	=> $G['worm_get_exp']
			);
		} else {
			$DB->rollBack();
			$result['msg'] = $L['Failure_Update'];
			$data = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('fruit_forest_worm', $data);
		}
		return $result;
	}
}





